package com.modifiertech.lineage.utils;

import com.modifiertech.lineage.Lineage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @description: default
 * @author: saliencemn
 * @mail: hackingmu@outlook.com
 * @date: 2024/10/8 19:57
 */
public class HttpUtil {

    /**获取get请求
     *
     * @param urlString
     * @return
     * @throws IOException
     */
    public String get(String urlString) throws IOException {
        StringBuilder response = new StringBuilder();
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            // 1. 创建 URL 对象
            URL url = new URL(urlString);

            // 2. 打开连接
            connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法为 GET
            connection.setRequestMethod("GET");

            // 4. 设置连接超时时间和读取超时时间
            connection.setConnectTimeout(30 * 1000);
            connection.setReadTimeout(30 * 1000);

            // 5. 获取响应代码，判断是否成功
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 6. 使用 BufferedReader 读取响应内容
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } else {
                Lineage.logger.error("HTTP 请求失败，响应码: {}", responseCode);
                throw new IOException("HTTP 请求失败，响应码: " + responseCode);
            }
        } catch (IOException e) {
            Lineage.logger.error("GET 请求失败，url: {}", urlString, e);
            throw e;
        } finally {
            // 7. 关闭连接和流
            if (reader != null) {
                reader.close();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }

        // 8. 返回完整的响应字符串
        return response.toString();
    }

}
